import { actErr, actLoaded } from '../client/interact'
import axios from 'axios'
import { nav } from '../client/window'
import { getToken, setToken } from '../client/window'
import { Req } from '../request/request'

export const prefix = 'http://127.0.0.1:3060'

export const axiosReq: Req = async function (
  method: 'post' | 'get' | 'delete' | 'put',
  url: string,
  options?: {
    data?: any,
    params?: any,
    noToken?: boolean,
    pure?: boolean,
    headers?: Record<string, string>,
    silent?: boolean
  }
) {
  if (import.meta.env.SSR) {
    return null
  }

  let headers: any = {}

  if (!options?.noToken) {
    headers.Authorization = getToken()
  }

  if (options?.headers) {
    headers = { ...headers, ...options?.headers }
  }

  return axios({ method, url, headers, data: options?.data, params: options?.params }).then((res) => {
    if (res?.headers?.Authorization) {
      setToken(res.headers.Authorization)
    }
    !options?.silent && actLoaded()
    return options?.pure ? res.data : res.data
  }).catch((err) => {
    !options?.silent && actErr(err?.response?.data?.message || '出错')
    if (err?.response?.data?.message === '请先登录') {
      nav('/')
    }
    return null
  })
}